package com.cgc.venus.server.user.controller;

import com.cgc.venus.server.core.bean.response.VenusResponse;
import com.cgc.venus.server.core.bean.response.VenusResponseStatus;
import com.cgc.venus.server.core.exception.VenusException;
import com.cgc.venus.server.core.utils.StringUtil;
import com.cgc.venus.server.user.bean.NodeDataBean;
import com.cgc.venus.server.user.bean.NodeLabelBean;
import com.cgc.venus.server.user.bean.PhysicalGroupBean;
import com.cgc.venus.server.user.inter.DemoService;
import com.cgc.venus.server.user.inter.InfrastructureService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by Administrator on 2017/6/3.
 */
@Api(value = "基础设施管理",description="基础设施管理所对应服务的api")
@RequestMapping("/infrastructure-admin")
@RestController
public class InfrastructureController {


    @Autowired
    private InfrastructureService InfrastructureServiceImpl;

    /*
根据关键字查询
 */
    @ApiOperation("物理分组查询")
    @RequestMapping(value = "/physicial/{queryKey}", method = RequestMethod.GET)
    @ResponseBody
    public VenusResponse<List<PhysicalGroupBean>> query(@RequestParam("queryKey") String queryKey) throws VenusException {
        List<PhysicalGroupBean> physicalGroupBeanList = InfrastructureServiceImpl.physicalLists(queryKey);
        VenusResponse<List<PhysicalGroupBean>> venusResponse = new VenusResponse<List<PhysicalGroupBean>>(VenusResponseStatus.OK, "", physicalGroupBeanList);
        return venusResponse;

    }
//物理分组名称重复性校验

    @ApiOperation("物理分组名称重复性校验")
    @RequestMapping(value = "/validate/{type}/{name}", method = RequestMethod.GET)
    @ResponseBody
    public VenusResponse<Boolean> validateTeamName(@PathVariable("type") String type, @PathVariable("name") String name) throws VenusException {
        boolean f = InfrastructureServiceImpl.validatePhysicalName(name, type);
        VenusResponse<Boolean> response = new VenusResponse<Boolean>(VenusResponseStatus.OK, "", f);
        return response;
    }

    /*
   新增物理分组信息
    */
    @ApiOperation("新增物理分组")
    @RequestMapping(value = "/physical", method = RequestMethod.POST)
    @ResponseBody
    public VenusResponse<Boolean> insert(@RequestBody PhysicalGroupBean physicalGroupBean ) throws VenusException {

        boolean c = InfrastructureServiceImpl.physicalSave(physicalGroupBean);
        VenusResponse<Boolean> venusResponse = new VenusResponse<Boolean>(VenusResponseStatus.OK, "保存成功", c);
        return venusResponse;
    }

    /*
删除物理分组信息
*/
    @ApiOperation("删除物理分组")
    @RequestMapping(value = "/physical/{physicalId}", method = RequestMethod.DELETE)
    @ResponseBody
    public VenusResponse<Boolean> infraDel(@PathVariable("physicalId") String physicalId ) throws VenusException {
        String name_En=InfrastructureServiceImpl.physicalQueryById(physicalId);
        List<String> labeList=InfrastructureServiceImpl.nodeLabelQuery();
        boolean f=false;
        for(int i=0;i<labeList.size();i++){
            if(labeList.get(i).equals(name_En)){
                f=true;
            }
        }
        if(f){
            throw new VenusException(VenusResponseStatus.FOREIGN_KEY_CONSTRAINTS,"不能删除该物理组，该物理组在使用中");
        }

        boolean c = InfrastructureServiceImpl.physicalDelById(physicalId);
        VenusResponse<Boolean> venusResponse = new VenusResponse<Boolean>(VenusResponseStatus.OK, "删除成功", c);
        return venusResponse;

    }

    /*
更新物理分组信息
*/
    @ApiOperation("更新物理分组")
    @RequestMapping(value = "/physical/{physicalId}", method = RequestMethod.PATCH)
    @ResponseBody
    public VenusResponse<Boolean> infraUpdate(@RequestBody PhysicalGroupBean infra) throws VenusException {

        boolean c = InfrastructureServiceImpl.physicalUpdateById(infra.getId(),infra.getRadio(),infra.getDescribed());
        VenusResponse<Boolean> venusResponse = new VenusResponse<Boolean>(VenusResponseStatus.OK, "更新成功", c);
        return venusResponse;

    }
//    节点维护--start
    @ApiOperation("查询物理分组名称")
    @RequestMapping(value = "/partition",method = RequestMethod.GET)
    @ResponseBody
    public VenusResponse<Object> partitionQuery() throws VenusException{
        List<Map<String,Object>> results= new ArrayList<Map<String, Object>>();
        results=InfrastructureServiceImpl.partitionQuery();
        Map<String,Object> datamap=new HashMap<String, Object>();
        String message="";
        if(results.size()>0){
            message="success";
            datamap.put("items",results);
        }

        VenusResponse<Object> venusResponse = new VenusResponse<Object>(VenusResponseStatus.OK,"", datamap);
        return venusResponse;
    }

    @ApiOperation("设置节点标签")
    @RequestMapping(value = "/partition",method = RequestMethod.POST)
    @ResponseBody
    public VenusResponse <Boolean> nodeLabelSet(@RequestBody NodeLabelBean nodeLabelBean) throws VenusException{
        if(StringUtil.isEmpty(nodeLabelBean.getNodename())||StringUtil.isEmpty(nodeLabelBean.getLabel())){
            throw new VenusException(VenusResponseStatus.NO_CONTENT,"标签信息不全");
        }
        Map<String,String> maps=new HashMap<String, String>();
        maps.put("physical.group",nodeLabelBean.getLabel());
        boolean f=InfrastructureServiceImpl.nodeLabelSet(nodeLabelBean.getNodename(),maps);
        VenusResponse<Boolean> venusResponse = new VenusResponse<Boolean>(VenusResponseStatus.OK,"设置成功",f);
        return venusResponse;

    }

    @ApiOperation("查询节点信息")
    @RequestMapping(value = "/node",method = RequestMethod.GET)
    @ResponseBody
    public VenusResponse <Object> nodeQueryByHostIP(@RequestParam(value="queryKey",required = false) String queryKey,@RequestParam(value="physicalGroup",required = false) String physicalGroup) throws VenusException{
        List<NodeDataBean> results= InfrastructureServiceImpl.nodeDataQuery();
        long total=0;
        if(results!=null&&results.size()>0){
            if(!StringUtil.isEmpty(queryKey)){
                results=results.stream().filter(ts -> (ts.getHostName().indexOf(queryKey) != -1
                        || ts.getIp().indexOf(queryKey) != -1)
                        || ts.getStatus().indexOf(queryKey)!=-1
                        || ts.getPhysicalZone().indexOf(queryKey)!=-1).collect(Collectors.toList());
            }
            if(!StringUtil.isEmpty(physicalGroup)){
                results=results.stream().filter(ts -> physicalGroup.equals(ts.getPhysicalZone())).collect(Collectors.toList());
            }
            total=results.size();
        }
        Map<String,Object> datamap=new HashMap<String, Object>();
        datamap.put("items",results);
        datamap.put("total",total);
        VenusResponse<Object> venusResponse = new VenusResponse<Object>(VenusResponseStatus.OK,"",datamap);
        return venusResponse;

//        if(StringUtil.isEmpty(queryKey)){
//            List<NodeDataBean> results= InfrastructureServiceImpl.nodeDataQuery();
//            Map<String,Object> datamap=new HashMap<String, Object>();
//            long total=0;
////        查询的有无结果都可以
//            if(results==null){
//                total=0;
//            }else{total=results.size();}
////        total=results.size();
//            datamap.put("items",results);
//            datamap.put("total",total);
//            VenusResponse<Object> venusResponse = new VenusResponse<Object>(VenusResponseStatus.OK,"",datamap);
//            return venusResponse;
//        }
//        List<NodeDataBean> results2= InfrastructureServiceImpl.nodeDataQuery();
//
//
////        List<NodeDataBean> results2=new ArrayList<NodeDataBean>();
////        for (int i=0;i<results.size();i++){
////            if(results.get(i).getHostName().equals(queryKey)
////                    ||results.get(i).getIp().equals(queryKey)
////                    ||results.get(i).getStatus().equals(queryKey)
////                    ||results.get(i).getPhysicalZone().equals(queryKey))
////                    {
////                NodeDataBean nodeDataBean=new NodeDataBean();
////                nodeDataBean.setHostName(results.get(i).getHostName());
////                nodeDataBean.setCPU(results.get(i).getCPU());
////                nodeDataBean.setDisk(results.get(i).getDisk());
////                nodeDataBean.setIp(results.get(i).getIp());
////                nodeDataBean.setMemory(results.get(i).getMemory());
////                nodeDataBean.setOperationDate(results.get(i).getOperationDate());
////                nodeDataBean.setPhysicalZone(results.get(i).getPhysicalZone());
////                nodeDataBean.setStatus(results.get(i).getStatus());
////                nodeDataBean.setPodNumbers(results.get(i).getPodNumbers());
////                nodeDataBean.setStartTime(results.get(i).getStartTime());
////                results2.add(nodeDataBean);
////            }
////        }
//        Map<String,Object> datamap=new HashMap<String, Object>();
//        long total=0;
////        查询的有无结果都可以
//        if(results2==null){
//            total=0;
//        }else{total=results2.size();}
////        total=results.size();
//        datamap.put("items",results2);
//        datamap.put("total",total);
//        VenusResponse<Object> venusResponse = new VenusResponse<Object>(VenusResponseStatus.OK,"",datamap);
//        return venusResponse;

    }
//    节点维护--end

    @ApiOperation("统计节点信息")
    @RequestMapping(value = "/node/stats",method = RequestMethod.GET)
    @ResponseBody
    public VenusResponse <Object> nodeStats() throws VenusException{
        List<NodeDataBean> all= InfrastructureServiceImpl.nodeDataQuery();
        List<NodeDataBean> ex= all.stream().filter(ts -> "Unknown".equals(ts.getStatus())).collect(Collectors.toList());
        List nodeLegendData=new ArrayList();
        nodeLegendData.add("总节点数:"+all.size()+"个");
        nodeLegendData.add("异常节点数:"+ex.size()+"个");
        nodeLegendData.add("正常节点数:"+(all.size()-ex.size())+"个");
        List nodeData=new ArrayList();
        Map mapTmp=new HashMap();
        mapTmp.put("value",all.size());
        mapTmp.put("name","总节点数:"+all.size()+"个");
        nodeData.add(mapTmp);
        mapTmp=new HashMap();
        mapTmp.put("value", ex.size());
        mapTmp.put("name","异常节点数:"+ex.size()+"个");
        nodeData.add(mapTmp);
        mapTmp=new HashMap();
        mapTmp.put("value", (all.size()-ex.size()));
        mapTmp.put("name","正常节点数:"+(all.size()-ex.size())+"个");
        nodeData.add(mapTmp);

        Map<String,Object> datamap=new HashMap<String, Object>();
        datamap.put("nodeLegendData",nodeLegendData);
        datamap.put("nodeData",nodeData);
        VenusResponse<Object> venusResponse = new VenusResponse<Object>(VenusResponseStatus.OK,"",datamap);
        return venusResponse;
    }

}